<template>
  <div class="page-wrap">
    <div class="page-header">
      <div class="page-title">
        调拨明细
        <el-tag type="info" effect="plain" class="title-tag">Transfer Detail</el-tag>
      </div>
      <div class="page-actions">
        <el-button @click="goBack" plain>返回</el-button>
        <el-button type="primary" @click="refreshData" :loading="loading">刷新</el-button>
        <!-- 出库操作 -->
        <el-button 
          v-if="canTransferOut" 
          type="warning" 
          @click="showTransferOutDialog"
          :loading="transferLoading"
        >
          调拨出库
        </el-button>
        <!-- 入库操作 -->
        <el-button 
          v-if="canTransferIn" 
          type="info" 
          @click="showTransferInDialog"
          :loading="transferLoading"
        >
          调拨入库
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading" shadow="never">
      <div v-if="transferData">
        <!-- 基本信息 -->
        <el-descriptions title="调拨单基本信息" :column="3" border>
          <el-descriptions-item label="调拨单号">{{ transferData.transferNo }}</el-descriptions-item>
          <el-descriptions-item label="调拨类型">{{ transferData.transferType }}</el-descriptions-item>
          <el-descriptions-item label="申请日期">{{ formatDateTime(transferData.applyDate) }}</el-descriptions-item>
          <el-descriptions-item label="单据状态">
            <el-tag :type="getBillStatusType(transferData.billStatus)" size="small">
              {{ transferData.billStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="出库状态">
            <el-tag :type="getOutStatusType(transferData.outStatus)" size="small">
              {{ getOutStatusText(transferData.outStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="入库状态">
            <el-tag :type="getInStatusType(transferData.inStatus)" size="small">
              {{ getInStatusText(transferData.inStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="调出仓库">{{ transferData.fromWarehouseName }}</el-descriptions-item>
          <el-descriptions-item label="调入仓库">{{ transferData.toWarehouseName }}</el-descriptions-item>
          <el-descriptions-item label="总数量">{{ formatNumber(transferData.totalQty) }}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ formatNumber(transferData.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ transferData.remark || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(transferData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(transferData.updateTime) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 调拨明细 -->
        <div style="margin-top: 20px;">
          <div class="detail-title">调拨明细</div>
          <el-table :data="transferData.lines" border stripe :header-cell-style="{background:'#f7f9fc'}">
            <el-table-column type="index" label="#" width="60" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="140" />
            <el-table-column prop="productNo" label="产品编号" width="120" />
            <el-table-column prop="specification" label="规格" width="120" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="fromLocationName" label="调出库位" width="120" />
            <el-table-column prop="toLocationName" label="调入库位" width="120" />
            <el-table-column prop="reqQty" label="调拨数量" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.reqQty) }}</template>
            </el-table-column>
            <el-table-column prop="outQty" label="已出库" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.outQty) }}</template>
            </el-table-column>
            <el-table-column prop="inQty" label="已入库" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.inQty) }}</template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.unitPrice) }}</template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120" align="right">
              <template #default="{ row }">{{ formatNumber(row.amount) }}</template>
            </el-table-column>
            <el-table-column label="进度" width="120" align="center">
              <template #default="{ row }">
                <el-progress 
                  :percentage="getProgressPercentage(row)" 
                  :status="getProgressStatus(row)"
                  :stroke-width="6"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 出库记录 -->
        <div v-if="outRecords.length > 0" style="margin-top: 20px;">
          <div class="detail-title">出库记录</div>
          <el-table :data="outRecords" border stripe :header-cell-style="{background:'#f7f9fc'}">
            <el-table-column type="index" label="#" width="60" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="140" />
            <el-table-column prop="productNo" label="产品编号" width="120" />
            <el-table-column prop="qty" label="出库数量" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.qty) }}</template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.unitPrice) }}</template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120" align="right">
              <template #default="{ row }">{{ formatNumber(row.amount) }}</template>
            </el-table-column>
            <el-table-column prop="operatorName" label="操作员" width="100" />
            <el-table-column prop="operatedAt" label="操作时间" width="160">
              <template #default="{ row }">{{ formatDateTime(row.operatedAt) }}</template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120" />
          </el-table>
        </div>

        <!-- 入库记录 -->
        <div v-if="inRecords.length > 0" style="margin-top: 20px;">
          <div class="detail-title">入库记录</div>
          <el-table :data="inRecords" border stripe :header-cell-style="{background:'#f7f9fc'}">
            <el-table-column type="index" label="#" width="60" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="140" />
            <el-table-column prop="productNo" label="产品编号" width="120" />
            <el-table-column prop="qty" label="入库数量" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.qty) }}</template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="100" align="right">
              <template #default="{ row }">{{ formatNumber(row.unitPrice) }}</template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120" align="right">
              <template #default="{ row }">{{ formatNumber(row.amount) }}</template>
            </el-table-column>
            <el-table-column prop="operatorName" label="操作员" width="100" />
            <el-table-column prop="operatedAt" label="操作时间" width="160">
              <template #default="{ row }">{{ formatDateTime(row.operatedAt) }}</template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120" />
          </el-table>
        </div>

        <!-- 操作日志 -->
        <div v-if="opLogs.length > 0" style="margin-top: 20px;">
          <div class="detail-title">操作日志</div>
          <el-table :data="opLogs" border stripe :header-cell-style="{background:'#f7f9fc'}">
            <el-table-column type="index" label="#" width="60" align="center" />
            <el-table-column prop="opType" label="类型" width="100" />
            <el-table-column prop="opContent" label="内容" min-width="320" />
            <el-table-column prop="opUser" label="操作人" width="120" />
            <el-table-column prop="createdAt" label="时间" width="180">
              <template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <el-empty v-else-if="!loading" description="暂无数据" />
    </el-card>


    <!-- 出库对话框 -->
    <el-dialog v-model="transferOutDialogVisible" title="调拨出库" width="800px">
      <el-form :model="transferOutForm" label-width="100px">
        <el-form-item label="操作员">
          <el-input v-model="transferOutForm.operatorName" placeholder="请输入操作员姓名" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" rows="3" v-model="transferOutForm.remark" placeholder="请输入出库备注" />
        </el-form-item>
      </el-form>
      <div style="margin-top: 20px;">
        <div class="detail-title">出库明细</div>
        <el-table :data="transferOutForm.items" border stripe>
          <el-table-column type="index" label="#" width="60" align="center" />
          <el-table-column prop="productName" label="产品名称" min-width="140" />
          <el-table-column prop="productNo" label="产品编号" width="120" />
          <el-table-column prop="reqQty" label="调拨数量" width="100" align="right">
            <template #default="{ row }">{{ formatNumber(row.reqQty) }}</template>
          </el-table-column>
          <el-table-column prop="outQty" label="已出库" width="100" align="right">
            <template #default="{ row }">{{ formatNumber(row.outQty) }}</template>
          </el-table-column>
          <el-table-column label="本次出库" width="120" align="center">
            <template #default="{ row, $index }">
              <el-input-number 
                v-model="transferOutForm.items[$index].qty" 
                :min="0" 
                :max="row.reqQty - row.outQty"
                :step="1"
                size="small"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="transferOutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTransferOut" :loading="transferLoading">确认出库</el-button>
      </template>
    </el-dialog>

    <!-- 入库对话框 -->
    <el-dialog v-model="transferInDialogVisible" title="调拨入库" width="800px">
      <el-form :model="transferInForm" label-width="100px">
        <el-form-item label="操作员">
          <el-input v-model="transferInForm.operatorName" placeholder="请输入操作员姓名" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" rows="3" v-model="transferInForm.remark" placeholder="请输入入库备注" />
        </el-form-item>
      </el-form>
      <div style="margin-top: 20px;">
        <div class="detail-title">入库明细</div>
        <el-table :data="transferInForm.items" border stripe>
          <el-table-column type="index" label="#" width="60" align="center" />
          <el-table-column prop="productName" label="产品名称" min-width="140" />
          <el-table-column prop="productNo" label="产品编号" width="120" />
          <el-table-column prop="outQty" label="已出库" width="100" align="right">
            <template #default="{ row }">{{ formatNumber(row.outQty) }}</template>
          </el-table-column>
          <el-table-column prop="inQty" label="已入库" width="100" align="right">
            <template #default="{ row }">{{ formatNumber(row.inQty) }}</template>
          </el-table-column>
          <el-table-column label="本次入库" width="120" align="center">
            <template #default="{ row, $index }">
              <el-input-number 
                v-model="transferInForm.items[$index].qty" 
                :min="0" 
                :max="row.outQty - row.inQty"
                :step="1"
                size="small"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="transferInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTransferIn" :loading="transferLoading">确认入库</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ReadClients, WriteClients } from '../../Urls/AxiosHelper'

const Read = ReadClients[0]
const Write = WriteClients[0]
const route = useRoute()
const router = useRouter()

interface TransferLine {
  id: number
  productId: number
  productName: string
  productNo: string
  specification: string
  unit: string
  fromLocationName: string
  toLocationName: string
  reqQty: number
  outQty: number
  inQty: number
  unitPrice: number
  amount: number
  createTime: string
  updateTime: string
}

interface TransferRecord {
  id: number
  transferId: number
  lineId: number
  productId: number
  productName: string
  productNo: string
  warehouseId: number
  warehouseName: string
  locationId: number
  locationName: string
  qty: number
  unitPrice: number
  amount: number
  operatorName: string
  operatedAt: string
  remark: string
}

interface TransferOpLog {
  id: number
  transferId: number
  opType: string
  opContent: string
  opUser: string
  createdAt: string
}


interface TransferOutForm {
  operatorName: string
  remark: string
  items: Array<{
    lineId: number
    productId: number
    productName: string
    productNo: string
    reqQty: number
    outQty: number
    qty: number
    unitPrice: number
  }>
}

interface TransferInForm {
  operatorName: string
  remark: string
  items: Array<{
    lineId: number
    productId: number
    productName: string
    productNo: string
    outQty: number
    inQty: number
    qty: number
    unitPrice: number
  }>
}

interface TransferDetail {
  transferId: number
  transferNo: string
  transferType: string
  applyDate: string
  billStatus: string
  outStatus: number
  inStatus: number
  fromWarehouseId: number
  fromWarehouseName: string
  toWarehouseId: number
  toWarehouseName: string
  totalAmount: number
  totalQty: number
  remark: string
  createTime: string
  updateTime: string
  lines: TransferLine[]
}

interface ApiResponse {
  code: number
  message: string
  data: TransferDetail
}

const loading = ref(false)
const transferData = ref<TransferDetail | null>(null)
const outRecords = ref<TransferRecord[]>([])
const inRecords = ref<TransferRecord[]>([])
const opLogs = ref<TransferOpLog[]>([])

// 对话框状态
const transferOutDialogVisible = ref(false)
const transferInDialogVisible = ref(false)

// 加载状态
const transferLoading = ref(false)

// 表单数据

const transferOutForm = ref<TransferOutForm>({
  operatorName: '',
  remark: '',
  items: []
})

const transferInForm = ref<TransferInForm>({
  operatorName: '',
  remark: '',
  items: []
})

// 计算属性 - 判断是否可以执行操作

const canTransferOut = computed(() => {
  const billStatus = transferData.value?.billStatus
  const outStatus = transferData.value?.outStatus
  return (billStatus === '审核通过' || billStatus === 'Approved' || String(billStatus) === '20') && 
         outStatus !== undefined && outStatus !== 2
})

const canTransferIn = computed(() => {
  const billStatus = transferData.value?.billStatus
  const outStatus = transferData.value?.outStatus
  const inStatus = transferData.value?.inStatus
  return (billStatus === '审核通过' || billStatus === 'Approved' || String(billStatus) === '20') && 
         outStatus !== undefined && outStatus > 0 && 
         inStatus !== undefined && inStatus !== 2
})

// 获取调拨明细
async function fetchTransferDetail() {
  const transferId = route.params.id || route.query.transferId
  if (!transferId) {
    ElMessage.error('缺少调拨单ID参数')
    return
  }

  loading.value = true
  try {
    console.log('获取调拨明细，transferId:', transferId)
    console.log('transferId类型:', typeof transferId)
    
    // 尝试多个可能的API路径
    let detailRes
    try {
      detailRes = await Read.get<ApiResponse>(`/wareread/api/AllocationQuery/GetTransferDetail/${transferId}`)
    } catch (err1: any) {
      console.log('第一个API路径失败，尝试备用路径:', err1.response?.status)
      try {
        detailRes = await Read.get<ApiResponse>(`/wareread/api/Allocation/GetTransferDetail/${transferId}`)
      } catch (err2: any) {
        console.log('第二个API路径失败，尝试第三个路径:', err2.response?.status)
        try {
          detailRes = await Read.get<ApiResponse>(`/wareread/api/AllocationQuery/GetTransferDetail`, { params: { transferId } })
        } catch (err3: any) {
          console.log('所有API路径都失败:', err3.response?.status)
          throw err3
        }
      }
    }
    
    if (detailRes.data.code === 200) {
      transferData.value = detailRes.data.data
    } else {
      ElMessage.error(detailRes.data.message || '获取调拨明细失败，已尝试仅加载出入库记录')
      // 不返回，继续加载出入库记录
    }

    // 尝试获取出库记录（可选，失败不影响主流程）
    try {
      const outRes = await Read.get<{ code: number; message: string; data: TransferRecord[] }>(`/wareread/api/AllocationQuery/GetTransferOutRecords/${transferId}`)
      if (outRes.data.code === 200) {
        outRecords.value = outRes.data.data || []
      }
    } catch (outErr) {
      console.log('获取出库记录失败，使用空数据:', outErr)
      outRecords.value = []
    }

    // 尝试获取入库记录（可选，失败不影响主流程）
    try {
      const inRes = await Read.get<{ code: number; message: string; data: TransferRecord[] }>(`/wareread/api/AllocationQuery/GetTransferInRecords/${transferId}`)
      if (inRes.data.code === 200) {
        inRecords.value = inRes.data.data || []
      }
    } catch (inErr) {
      console.log('获取入库记录失败，使用空数据:', inErr)
      inRecords.value = []
    }

    // 尝试获取操作日志
    try {
      const logRes = await Read.get<{ code: number; message: string; data: TransferOpLog[] }>(`/wareread/api/AllocationQuery/GetTransferOpLogs/${transferId}`)
      if (logRes.data.code === 200) {
        opLogs.value = logRes.data.data || []
      }
    } catch (logErr) {
      console.log('获取操作日志失败，使用空数据:', logErr)
      opLogs.value = []
    }
  } catch (err: any) {
    ElMessage.error((err?.response?.status === 404 ? '明细接口不存在' : (err?.message || '获取调拨明细失败')) + '，已尝试仅加载出入库记录')
  } finally {
    loading.value = false
  }
}

// 刷新数据
function refreshData() {
  fetchTransferDetail()
}

// 返回上一页
function goBack() {
  router.back()
}



// 显示出库对话框
function showTransferOutDialog() {
  if (!transferData.value) return
  
  transferOutForm.value = {
    operatorName: '',
    remark: '',
    items: transferData.value.lines.map(line => ({
      lineId: line.id,
      productId: line.productId,
      productName: line.productName,
      productNo: line.productNo,
      reqQty: line.reqQty,
      outQty: line.outQty,
      qty: 0,
      unitPrice: line.unitPrice
    }))
  }
  transferOutDialogVisible.value = true
}

// 执行出库
async function handleTransferOut() {
  if (!transferOutForm.value.operatorName.trim()) {
    ElMessage.warning('请输入操作员姓名')
    return
  }

  const hasValidQty = transferOutForm.value.items.some(item => item.qty > 0)
  if (!hasValidQty) {
    ElMessage.warning('请至少输入一个有效的出库数量')
    return
  }

  transferLoading.value = true
  try {
    const payload = {
      transferId: Number(transferData.value?.transferId),
      operatorName: transferOutForm.value.operatorName,
      remark: transferOutForm.value.remark,
      lines: transferOutForm.value.items
        .filter(item => item.qty > 0)
        .map(item => ({
          lineId: item.lineId,
          productId: item.productId,
          warehouseId: transferData.value?.fromWarehouseId ?? 0,
          locationId: 0,
          qty: item.qty,
          unitPrice: item.unitPrice
        }))
    }

    const res = await Write.post('/write/api/Allocation/TransferOut', payload)
    if (res.data.code === 200) {
      ElMessage.success('调拨出库成功')
      transferOutDialogVisible.value = false
      await fetchTransferDetail()
    } else {
      ElMessage.error(res.data.message || '调拨出库失败')
    }
  } catch (err: any) {
    console.error('出库操作失败:', err)
    ElMessage.error('出库功能暂未实现，请联系管理员')
  } finally {
    transferLoading.value = false
  }
}

// 显示入库对话框
function showTransferInDialog() {
  if (!transferData.value) return
  
  transferInForm.value = {
    operatorName: '',
    remark: '',
    items: transferData.value.lines.map(line => ({
      lineId: line.id,
      productId: line.productId,
      productName: line.productName,
      productNo: line.productNo,
      outQty: line.outQty,
      inQty: line.inQty,
      qty: 0,
      unitPrice: line.unitPrice
    }))
  }
  transferInDialogVisible.value = true
}

// 执行入库
async function handleTransferIn() {
  if (!transferInForm.value.operatorName.trim()) {
    ElMessage.warning('请输入操作员姓名')
    return
  }

  const hasValidQty = transferInForm.value.items.some(item => item.qty > 0)
  if (!hasValidQty) {
    ElMessage.warning('请至少输入一个有效的入库数量')
    return
  }

  transferLoading.value = true
  try {
    const payload = {
      transferId: Number(transferData.value?.transferId),
      operatorName: transferInForm.value.operatorName,
      remark: transferInForm.value.remark,
      lines: transferInForm.value.items
        .filter(item => item.qty > 0)
        .map(item => ({
          lineId: item.lineId,
          productId: item.productId,
          warehouseId: transferData.value?.toWarehouseId ?? 0,
          locationId: 0,
          qty: item.qty,
          unitPrice: item.unitPrice
        }))
    }

    const res = await Write.post('/write/api/Allocation/TransferIn', payload)
    if (res.data.code === 200) {
      ElMessage.success('调拨入库成功')
      transferInDialogVisible.value = false
      await fetchTransferDetail()
    } else {
      ElMessage.error(res.data.message || '调拨入库失败')
    }
  } catch (err: any) {
    console.error('入库操作失败:', err)
    ElMessage.error('入库功能暂未实现，请联系管理员')
  } finally {
    transferLoading.value = false
  }
}

// 状态类型映射
function getBillStatusType(status: string | number) {
  const statusStr = String(status)
  switch (statusStr) {
    case '10':
    case '待审核':
    case 'Pending Review':
      return 'warning'
    case '15':
    case '审核拒绝':
    case '审核驳回':
    case 'Audit Rejected':
      return 'danger'
    case '20':
    case '审核通过':
    case '已审核':
    case 'Approved':
    case 'Audited':
      return 'success'
    case '30':
    case '已完成':
    case 'Completed':
      return 'info'
    default: return 'info'
  }
}

function getOutStatusType(status: number) {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    default: return 'info'
  }
}

function getInStatusType(status: number) {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    default: return 'info'
  }
}

function getOutStatusText(status: number) {
  switch (status) {
    case 0: return '未出库'
    case 1: return '部分出库'
    case 2: return '已出库'
    default: return '未知'
  }
}

function getInStatusText(status: number) {
  switch (status) {
    case 0: return '未入库'
    case 1: return '部分入库'
    case 2: return '已入库'
    default: return '未知'
  }
}

// 计算进度百分比
function getProgressPercentage(row: TransferLine) {
  const total = row.reqQty
  const completed = Math.min(row.outQty, row.inQty)
  return total > 0 ? Math.round((completed / total) * 100) : 0
}

// 获取进度状态
function getProgressStatus(row: TransferLine) {
  const percentage = getProgressPercentage(row)
  if (percentage === 100) return 'success'
  if (percentage > 0) return 'warning'
  return 'exception'
}

// 格式化函数
function formatNumber(n: number | string) {
  const num = Number(n ?? 0)
  return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 2 }).format(num)
}

function formatDateTime(value: string) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchTransferDetail()
})
</script>

<style scoped>
.page-wrap {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-tag {
  vertical-align: middle;
}

.page-actions {
  display: flex;
  gap: 8px;
}

.detail-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #303133;
}
</style>


